package com.fiberhome.ztelauncher.core.page;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.fiberhome.ztelauncher.core.FocusCarry;
import com.fiberhome.zte_launcher.R;
import com.fiberhome.ztelauncher.core.page.model.AppType;
import com.fiberhome.ztelauncher.core.page.model.BaseType;
import com.fiberhome.ztelauncher.uilib.ScaleRecyclerView;
import com.fiberhome.ztelauncher.uilib.SpaceItemDecoration;
import com.fiberhome.ztelauncher.uilib.recycler.SpannableGridLayoutManager;
import com.fiberhome.ztelauncher.uilib.recycler.TwoWayLayoutManager;
import com.fiberhome.ztelauncher.resource.ResourceManager;
import com.fiberhome.ztelauncher.util.DataUtil;
import com.fiberhome.ztelauncher.util.DisplayUtil;
import com.fiberhome.ztelauncher.xml.bean.FileBean;
import com.fiberhome.ztelauncher.xml.bean.LaunchDataPage;
import com.fiberhome.ztelauncher.xml.bean.LauncherLayout;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by xc on 2018/3/20.
 * 描述：
 */

public class StaggeredFragment extends Fragment implements FocusCarry {

    public final static int BOTTOM = 0;
    public final static int LEFT = 1;
    public final static int TOP = 2;
    public final static int RIGHT = 3;
    private ScaleRecyclerView recyclerview;
    private int direction;
    private int column;
    private int row;
    private LauncherLayout.Page launcherLayoutPage;
    private LauncherLayout.PageCommon pageCommon;
    private FileBean pagebean;
    private View view;
    private MultiTypeAdapter mAdapter;

    private int focusDirection = -1;
    private BaseType lastFocusBT;

    //定义newInstance()实例
    public static StaggeredFragment newInstance(int direction, LauncherLayout.Page page, FileBean pagebean,
                                                LauncherLayout.PageCommon pageCommon) {
        StaggeredFragment fragment = new StaggeredFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("direction", direction);
        bundle.putSerializable("LauncherLayout_Page", page);
        bundle.putSerializable("pagebean", pagebean);
        bundle.putSerializable("PageCommon", pageCommon);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        direction = bundle.getInt("direction", 0);
        launcherLayoutPage = (LauncherLayout.Page) bundle.getSerializable("LauncherLayout_Page");
        pagebean = (FileBean) bundle.getSerializable("pagebean");
        pageCommon = (LauncherLayout.PageCommon) bundle.getSerializable("PageCommon");
        column = launcherLayoutPage.width;
        row = launcherLayoutPage.height;
    }

    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_staggered, container, false);
        recyclerview = (ScaleRecyclerView) view.findViewById(R.id.recyclerview);
        getPageData(pagebean);
        setRecyclerViewDirection();
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) recyclerview.getLayoutParams();
        lp.setMargins(pageCommon.margin.left,pageCommon.margin.top,pageCommon.margin.right,pageCommon.margin.bottom);
        recyclerview.setLayoutParams(lp);
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            focusDirection = -1;
        } else {
            needFocus();
        }
    }

    private void needFocus() {
        if (focusDirection > 0 && mAdapter != null) {
            mAdapter.setPreFocusedView(setPreFocusedView(focusDirection));
            mAdapter.requestFocus();
        }
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    private int setPreFocusedView(int direction) {
        int position = 0;
        BaseType nearBean = null;
        int lastPoint;
        int dis = -1;
        if (lastFocusBT != null) {
            if (direction == KeyEvent.KEYCODE_DPAD_LEFT) {
                //拿靠近最右边的
                lastPoint = lastFocusBT.getLayoutElement().top;
                for (BaseType bt : mAdapter.getModels()) {
                    LauncherLayout.Element e = bt.getLayoutElement();
                    if ((e.left + e.width - 1) == launcherLayoutPage.width) {
                        int distance = Math.abs(lastPoint - e.top);
                        if (dis < 0) {
                            dis = distance;
                            nearBean = bt;
                        } else {
                            if (dis > distance) {
                                dis = distance;
                                nearBean = bt;
                            }
                        }
                    }
                }
            } else if (direction == KeyEvent.KEYCODE_DPAD_RIGHT) {
                //拿靠近最左边的
                lastPoint = lastFocusBT.getLayoutElement().top;
                for (BaseType bt : mAdapter.getModels()) {
                    LauncherLayout.Element e = bt.getLayoutElement();
                    if (e.left == 1) {
                        int distance = Math.abs(lastPoint - e.top);
                        if (dis < 0) {
                            dis = distance;
                            nearBean = bt;
                        } else {
                            if (dis > distance) {
                                dis = distance;
                                nearBean = bt;
                            }
                        }
                    }
                }
            } else if (direction == KeyEvent.KEYCODE_DPAD_DOWN) {
                //拿靠近最上面的
                lastPoint = lastFocusBT.getLayoutElement().left;
                for (BaseType bt : mAdapter.getModels()) {
                    LauncherLayout.Element e = bt.getLayoutElement();
                    if (e.top == 1) {
                        int distance = Math.abs(lastPoint - e.left);
                        if (dis < 0) {
                            dis = distance;
                            nearBean = bt;
                        } else {
                            if (dis > distance) {
                                dis = distance;
                                nearBean = bt;
                            }
                        }
                    }
                }
            } else if (direction == KeyEvent.KEYCODE_DPAD_UP) {
                //拿靠近最下面的
                lastPoint = lastFocusBT.getLayoutElement().left;
                for (BaseType bt : mAdapter.getModels()) {
                    LauncherLayout.Element e = bt.getLayoutElement();
                    if ((e.top + e.height - 1) == launcherLayoutPage.height) {
                        int distance = Math.abs(lastPoint - e.left);
                        if (dis < 0) {
                            dis = distance;
                            nearBean = bt;
                        } else {
                            if (dis > distance) {
                                dis = distance;
                                nearBean = bt;
                            }
                        }
                    }
                }
            }
        }
        if (nearBean != null) {
            position = mAdapter.getModels().indexOf(nearBean);
        }
        return position;
    }

    private void getPageData(FileBean pageBean) {
        ResourceManager.getResourceManager().getPageData(pageBean, new Observer<LaunchDataPage>() {
            @Override
            public void onSubscribe(@NonNull Disposable disposable) {

            }

            @Override
            public void onNext(@NonNull LaunchDataPage launchDataPage) {
                judgeType(launchDataPage);
            }

            @Override
            public void onError(@NonNull Throwable throwable) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    public BaseType getSelectedBT() {
        if (mAdapter != null) {
            return mAdapter.getFocusBean();
        }
        return null;
    }

    private void setRecyclerViewDirection() {
        SpannableGridLayoutManager sgl;
//        if (direction == ContainerLayout.LEFT || direction == ContainerLayout.RIGHT) {
//            sgl = new SpannableGridLayoutManager(TwoWayLayoutManager.Orientation.VERTICAL, column, row);
//        } else {
//            sgl = new SpannableGridLayoutManager(TwoWayLayoutManager.Orientation.HORIZONTAL, column, row);
//        }
        sgl = new SpannableGridLayoutManager(TwoWayLayoutManager.Orientation.HORIZONTAL, column, row);
        recyclerview.setLayoutManager(sgl);

        //设置添加,移除item的动画,DefaultItemAnimator为默认的
        recyclerview.setItemAnimator(new DefaultItemAnimator());
//        DividerItemDecoration dividerV = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
//        dividerV.setDrawable(getResources().getDrawable(R.drawable.shape_recycler_divide));
//        DividerItemDecoration dividerH = new DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL);
//        dividerH.setDrawable(getResources().getDrawable(R.drawable.shape_recycler_divide));
//        recyclerview.addItemDecoration(dividerV);
//        recyclerview.addItemDecoration(dividerH);
        recyclerview.addItemDecoration(new SpaceItemDecoration(5));
    }

    /**
     * 判断是正常显示还是app类型显示
     *
     * @param launchDataPage
     */
    private void judgeType(LaunchDataPage launchDataPage) {
        List<LauncherLayout.Element> listElementLayout = DataUtil.sortPageLayout(launcherLayoutPage.elements.elements);
        List<LaunchDataPage.Element> listElementData = DataUtil.sortPageData(launchDataPage.elements.elements,
                listElementLayout);
        List<BaseType> listData = new ArrayList<BaseType>();
        if (TextUtils.isEmpty(launcherLayoutPage.pageType)) {
            for (int i = 0; i < listElementLayout.size(); i++) {
                listData.add(new BaseType(launcherLayoutPage.pageType, null, null, null).
                        getType(listElementLayout.get(i), listElementData.get(i), launcherLayoutPage));
            }
        } else {
            for (int i = 0; i < listElementLayout.size(); i++) {
                listData.add(new AppType(listElementLayout.get(i), listElementData.get(i), launcherLayoutPage,
                        view.getWidth(), view.getHeight()));
            }
            for (int i = 0; i < (column * row - listElementLayout.size()); i++) {
                listData.add(new BaseType(launcherLayoutPage.pageType, null, null, null));
                listData.add(new AppType(listElementLayout.get(i), listElementData.get(i), launcherLayoutPage,
                        view.getWidth(), view.getHeight()));
            }
        }
        mAdapter = new MultiTypeAdapter(getActivity(), recyclerview, listData);
        recyclerview.setAdapter(mAdapter);
        if (focusDirection > 0) {
            int focusPosition = setPreFocusedView(focusDirection);
            mAdapter.setFocusedWhenFreshed(focusPosition);

        }
    }

    public void focusItem(int direction, BaseType bt) {
        this.focusDirection = direction;
        this.lastFocusBT = bt;
    }

    @Override
    public boolean carry(int direction) {
        if (mAdapter != null) {
            BaseType bt = mAdapter.getFocusBean();
            if (bt == null) return false;
            LauncherLayout.Element el = bt.getLayoutElement();
            if (direction == KeyEvent.KEYCODE_DPAD_LEFT) {
                return el.left > 1;
            } else if (direction == KeyEvent.KEYCODE_DPAD_RIGHT) {
                return (el.left + el.width - 1) < launcherLayoutPage.width;
            } else if (direction == KeyEvent.KEYCODE_DPAD_DOWN) {
                return (el.top + el.height - 1) < launcherLayoutPage.height;
            } else if (direction == KeyEvent.KEYCODE_DPAD_UP) {
                return el.top > 1;
            }
        }
        return false;
    }

    @Override
    public boolean focus(boolean hasFocus) {
        if (hasFocus) {
            return mAdapter.requestFocus();
        }
        return true;
    }
}
